<?php
/**********************************************************************************
 
 	Display recipes for professions
	
	Copyright (C) 2010 Benjamin Thomas
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 	Author: Benjamin Thomas
	Email: thomas.ben@gmail.com
 	Created: 07/22/10
 	Revised: 
 
 	Calls: 
 
 ***********************************************************************************
 */
 
require_once(dirname(__FILE__) . '/../../lib/PageLayout.php');
require_once(dirname(__FILE__) . '/../../lib/MarketDB.php');
require_once(dirname(__FILE__) . '/../../lib/dateFunctions.php');
require_once(dirname(__FILE__) . '/../../lib/Recipe.php');

if (array_key_exists('p', $_GET)) {
	$prof = intval($_GET['p']);
} else {
	$prof = false;
}

$db = new MarketDB();

$db->loadItems();
if ($prof == 9) { leatherworking();
 }
if ($prof == 7) { milling(); }
if ($prof) {
	listRecipes($prof);
} else {
	listAll();
}



?>
<script id="source" language="javascript" type="text/javascript">
$(function () {
	$('#btnnorth').bind('click', function() { fadeToggle("#north"); });
	$('#btnoutland').bind('click', function() { fadeToggle("#outland"); });
	$('#btnvan').bind('click', function() { fadeToggle("#van"); });
	$('#btnrecipes').bind('click', function() { fadeToggle("#recipes"); });
})
</script>
<?php
function listRecipes($prof) {
	$db = $GLOBALS['db'];
	$list = $db->publicQuery("SELECT * FROM crafting WHERE profid = $prof ORDER BY gray DESC, spellname ASC");
	
	echo "<div id='btnrecipes'>Recipes</div>";
	$top = array();
	$top[] = "<a href='#' onClick='ajaxload(\"#content\",\"ajax/prof.php\")' class='small'><< Profession List</a>";
	echo  implode(" | ", $top);
	unset($top);
	
	echo "<hr /><div id='recipes'>";
	printPager();
	echo '<table id="recipelist" class="tablesorter">' . "\n";
	echo '<thead>';
	echo '<tr><th>Known</th><th>Item</th><th>Qty</th><th style="width:35px">CD</th><th>Moving Price</th>';
	echo '<th>Crafting Price</th><th>Return</th><th>Yield</th></tr>';
	echo '</thead><tbody>';
	foreach($list as &$row) {
		$tree = new Recipe($row['craftID'], $db);
		$tree->minimizeCosts();
		printRecipe($tree->toArray());
		unset($tree); unset ($row);
	}
	echo '</tbody></table></div><br />';
}

function printRecipe(&$tree, $prefix = '') {
	$db = &$GLOBALS['db'];
	$item = &$db->items[$tree['id']];
	$known = '<img src="images/check.png" />';
	$unknown  = '<img src="images/delete.png" />';
	
	echo '<tr>' . "\n";
	echo '<td>';
	if (array_key_exists('known',$tree)) {
		if ($tree['known']) { echo $known; } else { echo $unknown; }
	}
	echo '</td>';
	echo '<td>' . $prefix;
	$link = '<a href="#' . $tree['cid'] . '" onClick="showRecipe(' . $tree['cid'] . ')">' . $item['name'] . '</a>';
	echo '<img src="images/icons/' . $item['icon'] . '" style="width:20px; height: 20px;" /> ' . $link . '</td>';
	if ($tree['in'] == 0) { $count = $tree['out']; } else { $count = $tree['in']; }
	echo '<td>' . $count . '</td>' . "\n";
	if ($tree['in']) { $t = $tree['in']; }  else { $t = 1; }
	echo '<td>' . $tree['cd'] . 'h</td>';
	$vf = ($tree['price'] * $t);
	echo '<td>' . getGold($vf) . '</td>' . "\n";
	if (array_key_exists('cost', $tree)) {
		$vi = $tree['cost']; // / $tree['out'];
		echo '<td>' . getGold($vi) . '</td>';
		echo "<td>" .  getGold(round($vf - $vi)) . "</td>";
		echo '<td>' . round(safediv($vf - $vi,$vi)*100) . '%</td>';
	}
	echo '</tr>' . "\n";
	unset($item);
}

function getPrice($id) {
	$db = $GLOBALS['db'];
	if (!array_key_exists($id, $db->items)) {
		$db->loadItems($id);
	}
	if ($db->items[$id]['price']) {
		return $db->items[$id]['price'];
	}
	if(!array_key_exists('percentile', $db->items[$id])) {
		$db->items[$id]['percentile'] = $db->getMovingPrice($id, 7);
	}
	return $db->items[$id]['percentile'];
}


function milling() {
	$herbs = array(36905,36903,36906,37921,36901,36904,36907);
	$rare = array(.25,.25,.25,.125,.125,.125,.125);
	$common = array(1.5,1.5,1.5,1.25,1.25,1.25,1.25);
	echo "<div id='btnnorth'>Northrend Milling</div><hr /><div id='north'>";
	printMilling($herbs, $rare, $common);
	echo '</div>';
}

function printMilling($herbs, $rare, $common) {

	$db = $GLOBALS['db'];

	echo '<table class="tablesorter"><thead><tr>';
	echo '<th></th><th></th>';
	foreach($herbs as $id) { 
		echo '<th><img src="images/icons/' . $db->items[$id]['icon'] . '" style="width:20px; height: 20px;" /></th>';	
	}
	echo '</tr></thead>';
	echo '<tbody>';
	echo '<tr><td>Price Per Stack</td><td></td>';
	foreach($herbs as $id) {
		$price = getPrice($id);
		echo '<td>' . getGold(20 * $price) . '</td>';	
	}
	echo '</tr>';	
	echo '<tr><td>Price Per Mill</td><td></td>';
	foreach($herbs as $id) {
		$price = getPrice($id);
		echo '<td>' . getGold(5 * $price) . '</td>';	
	}
	echo '</tr>';
	echo '<tr><td><img src="images/icons/' . $db->items[43126]['icon'] . '" style="width:20px; height: 20px;" /> Ink of the Sea</td>';
	echo '<td>' . getGold(getPrice(43126)) . '</td>	';
	for ($i = 0; $i < count($herbs); $i++) {
		echo '<td>' . $common[$i] . '</td>'; 
	}	
	echo '</tr>';
	echo '<tr><td><img src="images/icons/' . $db->items[43127]['icon'] . '" style="width:20px; height: 20px;" /> Snowfall Ink</td>';
	echo '<td>' . getGold(getPrice(43127)) . '</td>';
	for ($i = 0; $i < count($herbs); $i++) {
		echo '<td>' . $rare[$i] . '</td>'; 
	}
	echo '</tr>';
	echo '<tr><td>Profit Per Stack</td><td></td>';
	$vf = getPrice(43127) + getPrice(43126);
	for ($i = 0; $i < count($herbs); $i++) {
		$return = ((getPrice(43127) * $rare[$i]*4) + (getPrice(43126) * $common[$i]*4)) - (getPrice($herbs[$i])*20);
		echo '<td>' . getGold($return) . '</td>'; 
	}
	echo '</tr>';
	echo '</tbody></table>';
	echo '</div><br />';
}

function leatherworking() {
	echo "<div id='btnnorth'>Northrend Leather</div><hr /><div id='north'>";
	printMatTable(44128);
	echo '</div><br />';
/*
	echo "<div id='btnoutland'>Outland Leather</div><hr /><div id='outland'>";
	printMatTable(23793);
	echo '</div><br />';

	echo "<div id='btnvan'>Vanilla Leather</div><hr /><div><div id='van'>";
	printMatTable(8170);
	echo '</div><br />';
*/
}

function printMatTable($find) {
	$db = $GLOBALS['db'];
	$treeid = array();
	$treecount = array(1);
	$treeprice = array();


	while ($find) {
		$treeid[] = $find;
		$mats = $db->publicQuery("SELECT craftid FROM crafting WHERE productid = $find");
		if ($mats) {
			if ($input = $db->publicquery("SELECT inputid, inputcount FROM craftinginputs WHERE craftid = " . $mats[0]['craftid'])) {
				$treecount[] = $input[0]['inputcount'];
				$find = $input[0]['inputid'];
			} else {
				$find = false;
			}
		} else {
			$find = false;
		}
	}

	echo '<table cellspacing=10>';
	echo '<tr><td>Item</td><td>Price</td>';
	$cols = count($treeid) - 1;
	for($i = 0; $i < $cols; $i++) {
		echo '<td align="center"><img src="images/icons/' . $db->items[$treeid[$i]]['icon'] . '" style="width:30px; height: 30px;" /></td>';
	}
	echo '</tr>';

	for($i = 0; $i < count($treeid); $i++) {
		echo '<tr><td><img src="images/icons/' . $db->items[$treeid[$i]]['icon'] . '" style="width:20px; height: 20px;" /> ' . $db->items[$treeid[$i]]['name'] . "</td>";
		$treeprice[$i] = getPrice($treeid[$i],7);
		echo '<td align=right>' . getGold($treeprice[$i]) . '</td>';
		for ($j = 0; $j < $cols; $j++) {
			if ($i <= $j) { 
				echo "<td align=center>x</td>"; 
			} else {
				$val = 1;
				$price = 1;
				$k = $i;
				while ($k - $j > 0) {
					$val = $val * $treecount[$k];
					$k--;
				}
				if ($treeprice[$i] * $val < $treeprice[$j]) {
					//$style = 'border-style:solid;border-width:2px; border-color: green';
					$style = 'background-color: #9CE396';
				} else {
					//$style = 'border-style:solid;border-width:2px; border-color: red;';
					$style = 'background-color: #BA737C';
				}
				echo "<td align=right style='$style'>" . getGold($treeprice[$i] * $val) . "</td>";
			}
		}
		echo '</tr>';
	}
	echo '</table>';
}

function listAll() {
	$db = $GLOBALS['db'];
	$list = $db->publicQuery("SELECT name, icon, id FROM profession");

	$i = 1;
	echo '<table style="width: 95%; margin-left: auto; margin-right: auto;"><tr>';
	foreach($list as &$row) {
	
		if (!$icon = $row['icon']) { 
			$icon = '404.png';
		}
		$id = $row['id'];
		echo '<td style="font-size:1.5em;">';
		echo '<img src="images/icons/' . $icon . '" /> <a href="#prof?' . $id . '" onclick="ajaxload(\'#content\', \'ajax/prof.php?p=' . $id . '\')">' . $row['name'] . '</a><br />';
		echo '</td>';
		if ($i % 4 == 0) { echo '</tr><tr>'; }
		$i++;
	}
	echo '</tr></table>';
}
?>
  <script>
 $(document).ready(function() 
    {     
		$(function() { 
        $("#recipelist").tablesorter({ 
            headers: { 
                0: { sorter: false },
				1: { sorter: 'item' },
				2: { sorter: false },
				3: { sorter: 'digit' },
				4: { sorter: 'gold' },
				5: { sorter: 'gold' },
				6: { sorter: 'gold' },
				7: { sorter: 'percent' },
            },
			widthFixed: true,
			widgets: ['zebra']			
        }); 

		$("#recipelist").tablesorterPager({container: $("#pager")});
    });      
    } 
);
</script>